package com.huilian.iotbox.admin.wap.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.huilian.iotbox.admin.wap.dao.LedgerCommodityDao;
import com.huilian.iotbox.admin.wap.dao.LedgerMerchantDao;
import com.huilian.iotbox.admin.wap.dao.LedgerMerchantRecordDao;
import com.huilian.iotbox.admin.wap.dao.MerchantStoreDao;
import com.huilian.iotbox.admin.wap.service.LedgerMerchantService;
import com.huilian.iotbox.admin.wap.service.UserService;
import com.huilian.iotbox.data.common.ServerResponse;
import com.huilian.iotbox.data.dto.LedgerMerchantDto;
import com.huilian.iotbox.data.dto.LedgerMerchantRecordDto;
import com.huilian.iotbox.data.dto.MerchantStoreDto;
import com.huilian.iotbox.data.enums.LedgerMerchantFailureStatusEunm;
import com.huilian.iotbox.data.enums.RoleEnum;
import com.huilian.iotbox.data.po.LedgerMerchant;
import com.huilian.iotbox.data.po.MerchantStore;
import com.huilian.iotbox.data.utils.DateTimeUtils;
import com.huilian.iotbox.data.vo.LedgerMerchantRecordVo;
import com.huilian.iotbox.data.vo.LedgerMerchantVo;
import com.huilian.iotbox.data.vo.UserVo;
import lombok.val;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

@Service
public class LedgerMerchantServiceImpl implements LedgerMerchantService {
    @Resource
    private LedgerMerchantDao ledgerMerchantDao;
    @Resource
    private MerchantStoreDao merchantStoreDao;
    @Resource
    private UserService userService;
    @Resource
    private PasswordEncoder passwordEncoder;
    @Resource
    private LedgerMerchantRecordDao ledgerMerchantRecordDao;
    @Resource
    private LedgerCommodityDao ledgerCommodityDao;
    /**
     * 查询场地对应分账信息
     * */
    @Override
    public ServerResponse findAreaSubLedgerMerchantByMerchantStoreId(LedgerMerchantDto ledgerMerchantDto) {
        MerchantStoreDto merchantStoreCondition = new MerchantStoreDto();
        merchantStoreCondition.setId(ledgerMerchantDto.getMerchantStoreId());
        merchantStoreCondition.setUserId(ledgerMerchantDto.getUserInfo().getId());
        MerchantStore merchantStore = merchantStoreDao.findOneMerchantStoreByCondition(merchantStoreCondition);
        if(ObjectUtils.isEmpty(merchantStore)){
            ServerResponse.createBySuccess("场地不存在");
        }
        Map<String,Object> map = new HashMap<>();
        try {
            List<LedgerMerchantVo> ledgerMerchantVoList = ledgerMerchantDao.findAreaSubLedgerMerchantByMerchantStoreId(ledgerMerchantDto);
            //查询商品
            if(ledgerMerchantVoList.size() > 0 && ledgerMerchantVoList.get(0).getDesignatedGoodsType().compareTo(1) == 0){
                Integer[] checkboxCommodityIdArray = ledgerCommodityDao.findLedgerCommodityByLedgerMerchantIdList(ledgerMerchantVoList.get(0).getLedgerMerchantId());
                map.put("checkboxCommodityIdArray",checkboxCommodityIdArray);
            }
            map.put("merchantStore",merchantStore);
            map.put("ledgerMerchantVoList",ledgerMerchantVoList);
        }catch (Exception e){
            e.printStackTrace();
        }
        return ServerResponse.createBySuccess(map);
    }

    /**
     * 停止分账
     * */
    @Override
    public ServerResponse updateFailureTime(LedgerMerchantDto ledgerMerchantDto) throws ParseException {
        //不包含1，2，3，无权限操作
        Integer[] roleIdArray = {
                RoleEnum.AGENT.getRoleId(),
                RoleEnum.SUPER_ADMINISTRATOR.getRoleId(),
                RoleEnum.MERCHANT.getRoleId()
        };
        boolean contains = Arrays.asList(roleIdArray).contains(ledgerMerchantDto.getUserInfo().getRoleId());
        if(!contains){
            return ServerResponse.createByErrorMessage("暂无操作权限！");
        }
        UserVo userVo = userService.findOperatePasswordByUserId(ledgerMerchantDto.getUserInfo().getId());
        boolean matches = passwordEncoder.matches(ledgerMerchantDto.getOperatePassword(), userVo.getOperatePassword());
        if (!matches) {
            return ServerResponse.createByErrorMessage("操作密码不正确");
        }
        //查询生效的场地
        LedgerMerchantVo ledgerMerchantVo = ledgerMerchantDao.findOneExistLedgerMerchant(ledgerMerchantDto);
        if(ObjectUtils.isEmpty(ledgerMerchantVo)){
            return ServerResponse.createByErrorMessage("该场地没有生效");
        }
        LedgerMerchant ledgerMerchant = new LedgerMerchant();
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        ledgerMerchant.setId(ledgerMerchantVo.getId());
        if(ledgerMerchantDto.getLapseType() == 1){
            ledgerMerchant.setFailureTime(format.parse(DateTimeUtils.currTime()));
        }else{
            ledgerMerchant.setFailureTime(format.parse(DateTimeUtils.getSomeDayLaterStartTime(1)));
        }
        Integer result = ledgerMerchantDao.update(ledgerMerchant);
        if(result == 0){
            throw new RuntimeException("停止分账失败");
        }
        return ServerResponse.createBySuccess(ledgerMerchant);
    }

    /**
     * 查询分账比例记录
     * */
    @Override
    public ServerResponse ledgerProportionRecord(LedgerMerchantDto LedgerMerchantDto) {
        PageHelper.startPage(LedgerMerchantDto.getPageNum(), LedgerMerchantDto.getPageSize(),"lm.createTime desc");
        //查询所有的分账场地记录
        List<LedgerMerchantVo> ledgerMerchantVoList = ledgerMerchantDao.findLedgerMerchantByUserId(LedgerMerchantDto);
        if(ledgerMerchantVoList.size() == 0){
            return ServerResponse.createBySuccess("没有分账记录");
        }
        for (LedgerMerchantVo lv : ledgerMerchantVoList){
            List<LedgerMerchantRecordVo> recordList = ledgerMerchantRecordDao.findLedgerMerchantRecordByLedgerMerchantId(lv.getId());
            lv.setLedgerMerchantRecordVoList(recordList);
        }
        PageInfo pageInfo = new PageInfo(ledgerMerchantVoList);
        return  ServerResponse.createBySuccess(pageInfo);
    }
}
